<template>
  <div>
    <!-- 视频类型 -->
    <video ref="videoPlayer" class="video-js" />
  </div>
</template>

<script>
import videojs from "video.js";
import "video.js/dist/video-js.css";
import video_zhCN from "video.js/dist/lang/zh-CN.json";
videojs.addLanguage("zh-CN", video_zhCN);
export default {
  data() {
    return {
      collectionInfo: {}, // 合集信息
      curFile: {}, // 当前文件
      resourcesList: [], // 资源列表
      tabList: [
        {
          name: "相关资源",
        },
      ],
    };
  },
  created() {},
  mounted() {
    this.switchFile();
  },
  beforeDestroy() {
    if (this.player) {
      this.player.dispose();
    }
  },
  methods: {
    switchFile() {
      this.initializeVideoPlayer(
        "https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8"
      );
    },
    initializeVideoPlayer(videoUrl) {
      if (this.player) {
        this.player.src(videoUrl);
        return;
      }
      const options = {
        techOrder: ["html5"], // 指定使用HTML5播放器
        playbackRates: [0.5, 1, 2],
        controls: true, // 显示控制条
        sources: [
          {
            src: videoUrl,
            type: "application/x-mpegURL", // 指定M3U8类型
          },
        ],
      };

      this.player = videojs(this.$refs.videoPlayer, options);

      this.player.getChild("ControlBar").addChild("button", {
        className: "vjs-camera-control vjs-control",
        controlText: "截图",
        innerHTML: '<span class="vjs-icon-placeholder"></span>',
        clickHandler: () => {
          const canvas = document.createElement("canvas");
          canvas.width = this.player.videoWidth();
          canvas.height = this.player.videoHeight();
          console.log(canvas);
          console.log(this.player.el());
          canvas
            .getContext("2d")
            .drawImage(this.player.el().querySelector("video"), 0, 0);
          const screenshotDataUrl = canvas.toDataURL("image/png");
          const a = document.createElement("a");
          a.style.display = "none";
          a.href = screenshotDataUrl;
          a.download = "fileName";
          document.body.appendChild(a);
          a.click();

          // 在控制台中显示截图数据URL
          console.log(screenshotDataUrl);
        },
      });

      // 将截图按钮添加到控制栏
      // this.player.controlBar.addChild(screenshotButton)

      // 启用倍速播放
      this.player.ready(() => {
        console.log(this.player.controlBar);
        this.player.controlBar.addChild("PlaybackRateMenuButton");
      });
    },
    // 下载
    handleDownload() {
      window.open(this.curFile.fileUrl);
    },
    // 改变路由参数，方便页面刷新时，还是选中当前章节和视频
    toiClassroom() {
      this.$router.push({
        name: "i课堂",
        params: {
          comName: "TeachingResources",
        },
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.video-js {
  margin: 50px 15%;
  width: 902.96px;
  height: 505.04px;
}
</style>
